#!/bin/bash
#########################################################################
#
# File:         ngraph
# Description:  create Panel of Kibana for nagios performance data.
# Language:     GNU Bourne-Again SHell
# Version:      1.1.1
# Date:         2017-12-1
# Corp.:        liaoyichang
# Author:       atdmliaod@tom.com
#########################################################################

SOURCE="$( cd "$( dirname "$0"  )" && pwd  )"
JSON_CMD=@tools@/jsonread
ES_CMD=@tools@/minies
ES_SERVER=@es_server@
ES_PORT=9200
IDC="@idc_name@"

service_name=""
host=""
mode="set"

print_help_msg(){
        print_version
        $ECHO "Usage: $0 -h to get help."
        $ECHO
        $ECHO 'Report bugs to: liaoyq@tom.com'
}
print_full_help_msg(){
        print_version
        $ECHO "Usage:"
        $ECHO "$0  [ -h ] -s service name -n host name"
}
print_version(){
        $ECHO $(cat $0 | head -n 7 | tail -n 1|sed 's/\# //')
}

to_debug(){
                $ECHO "`date +'%Y-%m-%d:%H:%M:%S'`|$*"
}
to_debugn(){
                $ECHO -n "$*"
}
case "$(uname -s)"
        in
        SunOS)
        ECHO="echo"
        ;;
        Linux)
        ECHO="echo -e"
        ;;
        *)
        ECHO="echo"
        ;;
esac
if [ ! -x "$JSON_CMD" ];then
        $ECHO "Can not found command $JSON_CMD, pleas check it"
        exit 3
fi
if [ ! -x "$ES_CMD" ];then
        $ECHO "Can not found command $ES_CMD, pleas check it"
        exit 3
fi

	while getopts :hs:n:l OPTION
	do
		case $OPTION
			in
      s)
			  service_name=$OPTARG
      ;;
      n)
        host=$OPTARG
      ;;
      l)
        mode="list"
      ;;
			h)
			print_full_help_msg
			exit 3
			;;			
			?)
			$ECHO "Error: Illegal Option."
			print_help_msg
			exit 3
			;;
		esac
	done		
sdate=`date +'%Y-%m'`
stime=`date +'%Y-%m-%dT%H:%M:%S'`
if [ "$host""ZZZ" == "ZZZ" ]; then
    $ECHO "Error: missing  parameter host"
    print_full_help_msg
    exit 3
fi
HOLD1=/tmp/ngraph.$$
HOLD2=/tmp/ngraph_tmp.$$

if [ "$mode" == "list" ]; then
    if [ "$service_name""ZZZ" == "ZZZ" ]; then
        $ES_CMD -s $ES_SERVER -m GET -u "/.kibana/dashboard/_search?q=title:\"$IDC-$host\"&pretty" > $HOLD1
    else
        $ES_CMD -s $ES_SERVER -m GET -u "/.kibana/visualization/_search?q=title:\"$IDC-$host-$service_name\"&pretty" > $HOLD1
    fi
    cat $HOLD1
    $JSON_CMD -f _id $HOLD1    
    rm -rf $HOLD1
    exit 0
fi

if [ "$service_name""ZZZ" == "ZZZ" ]; then
    $ECHO "Error: missing parameter service name"
    print_full_help_msg
    exit 3
fi

$ECHO "setup graph for $service_name of $host"

$ES_CMD -s $ES_SERVER -m GET -u "/.kibana/index-pattern/_search?q=title:perfdata-&size=1" > $HOLD1
#cat $HOLD1
perf_id=`$JSON_CMD -f _id $HOLD1`
$ECHO "Found perfdata index id = $perf_id"
if [ "$perf_id""ZZZ" == "ZZZ" ]; then
    $ECHO "Error: can not found perfdata index"
    cat $HOLD1
    rm -rf $HOLD1
    exit 1
fi
perf_id=`$ECHO $perf_id|awk -F'"' '{print $4 }'`

$ES_CMD -s $ES_SERVER -m GET -u "/.kibana/visualization/_search?q=title:\"$IDC-$host-$service_name\"&pretty" > $HOLD1
graph_id=`$JSON_CMD -f _id $HOLD1|awk -F'"' '{print $4}'`
if [ "$graph_id""ZZZ" != "ZZZ" ]; then
    $ECHO "Found visualization id=$graph_id"
fi

$ES_CMD -s $ES_SERVER -m GET -u "/perfdata-$sdate/$service_name/_search?q=name:$host+and+idc:$IDC&size=1" > $HOLD1
$ECHO "Fetch one reord:"
$ECHO `cat $HOLD1`

fields=`$JSON_CMD -f _source $HOLD1|grep -v '@\|{\|}\|"name"\|"severity"\|"idc"\|.Interval'|awk -F'"' '{print $2}'`
if [ "$fields""ZZZ" == "ZZZ" ]; then
    $ECHO "Error: can not found fields of $service_name"
    exit 1
fi
$ECHO "Setup Filed: $fields"

$ECHO '{' > $HOLD1
$ECHO "   \"title\" : \"$IDC-$host-$service_name\"," >> $HOLD1
$ECHO -n '   "visState": "' >> $HOLD1

$ECHO -n "{\"title\":\"$IDC-$host-$service_name\",\"type\":\"line\"," > $HOLD2
$ECHO -n '"params":{"addLegend":true,"addTimeMarker":false,"addTooltip":true,"categoryAxes":[' >> $HOLD2
$ECHO -n '{"id":"CategoryAxis-1","labels":{"show":true,"truncate":100},"position":"bottom","scale":{"type":"linear"},"show":true,"style":{},"title":{"text":"@timestamp per 10 minutes"},"type":"category"}],' >>$HOLD2
$ECHO -n '"grid":{"categoryLines":true,"style":{"color":"#eee"}},"legendPosition":"bottom","seriesParams":[' >> $HOLD2
#      {"data":{"id":"1","label":"load"},"drawLinesBetweenPoints":true,"mode":"normal","show":"true","showCircles":true,"type":"line","valueAxis":"ValueAxis-1"},
 #     {"data":{"id":"3","label":"mem"},"drawLinesBetweenPoints":true,"mode":"normal","show":true,"showCircles":true,"type":"line","valueAxis":"ValueAxis-1"},
  #    {"data":{"id":"5","label":"w\\"ho"},"drawLinesBetweenPoints":true,"mode":"normal","show":true,"showCircles":true,"type":"line","valueAxis":"ValueAxis-1"}
index=1
for field in $fields; do
if [ "$index" == "1" ]; then
    $ECHO -n "{\"data\":{\"id\":\"$index\",\"label\":\"$field\"}," >> $HOLD2
else
    $ECHO -n ",{\"data\":{\"id\":\"$index\",\"label\":\"$field\"}," >> $HOLD2
fi

$ECHO -n '"drawLinesBetweenPoints":true,"mode":"normal","show":"true","showCircles":true,"type":"line","valueAxis":"ValueAxis-1"}' >> $HOLD2
let index++
done  
$ECHO -n '],"times":[],"type":"line","valueAxes":[' >> $HOLD2
$ECHO -n '{"id":"ValueAxis-1","labels":{"filter":false,"rotate":0,"show":true,"truncate":100},"name":"LeftAxis-1","position":"left",' >> $HOLD2
$ECHO -n '"scale":{"mode":"normal","type":"linear"},"show":true,"style":{},"title":{"text":""},"type":"value"}]},"aggs":[' >> $HOLD2
#     {"id":"1","enabled":true,"type":"avg","schema":"metric","params":{"field":"system.load","customLabel":"load"}},
 #    {"id":"2","enabled":true,"type":"date_histogram","schema":"segment","params":{"field":"@timestamp","interval":"auto","customInterval":"2h","min_doc_count":1,"extended_bounds":{}}},
 #    {"id":"3","enabled":true,"type":"avg","schema":"metric","params":{"field":"system.mem","customLabel":"mem"}},
 #    {"id":"4","enabled":true,"type":"avg","schema":"metric","params":{"field":"system.cpu","customLabel":"cpu"}},
 #    {"id":"5","enabled":true,"type":"avg","schema":"metric","params":{"field":"system.wio","customLabel":"w\\"ho"}}
$ECHO -n '{"id":"0","enabled":true,"type":"date_histogram","schema":"segment","params":{"field":"@timestamp","interval":"auto","customInterval":"2h","min_doc_count":1,"extended_bounds":{}}}' >> $HOLD2
index=1
for field in $fields; do
tmp=${field#*.}
$ECHO -n ",{\"id\":\"$index\",\"enabled\":true,\"type\":\"avg\",\"schema\":\"metric\",\"params\":{\"field\":\"$field\",\"customLabel\":\"$tmp\"}}" >> $HOLD2
let index++
done
$ECHO -n '],"listeners":{}}' >> $HOLD2
jsonencode -f $HOLD2 >> $HOLD1
$ECHO '",' >> $HOLD1
$ECHO '   "uiStateJSON": "{}",' >> $HOLD1
$ECHO "   \"description\":\"all service of $host\"," >> $HOLD1
$ECHO '   "version": 1,' >>$HOLD1
$ECHO '   "kibanaSavedObjectMeta":{' >> $HOLD1
$ECHO "     \"searchSourceJSON\": \"{\\\"index\\\":\\\"$perf_id\\\",\\\"query\\\":{\\\"query_string\\\":{\\\"analyze_wildcard\\\":true,\\\"query\\\":\\\"name=$host idc=$IDC\\\"}},\\\"filter\\\":[]}\"" >> $HOLD1
$ECHO '   }' >> $HOLD1
$ECHO ' }' >> $HOLD1

if [ "$graph_id""ZZZ" == "ZZZ" ]; then
    minies -v 4 -s $ES_SERVER -m POST -d $HOLD1 -u "/.kibana/visualization/"
else
    minies -v 4 -s $ES_SERVER -m PUT -d $HOLD1 -u "/.kibana/visualization/$graph_id"
fi

rm -rf $HOLD1
rm -rf $HOLD2
